<template>
  <div>
    <!-- 到顶部 -->
    <div class="top_box">
      <span>角色名称：</span>
      <el-input v-model.trim="addData.name" placeholder="角色名称" clearable />
      <span>描述信息：</span>
      <el-input v-model.trim="addData.desc" placeholder="描述信息" clearable />
      <el-button type="primary" @click="addRole">添加角色</el-button>
    </div>
    <div style="margin-top: 20px">
      <!-- 列表 -->
      <el-table :data="infoList" border>
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="desc" label="说明" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <div v-if="row.id != 1">
              <el-button type="primary" @click="editRole(row)">修改</el-button>
              <el-button type="primary" @click="getPermission(row.id)">授权</el-button>
              <el-button type="danger" @click="showDele(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin: 20px 0px">
      <!-- 分页组件 -->
      <ElPagination
        :total="pageInfo.total"
        :limit="pageInfo.limit"
        @changeReq="changeConfig"
      ></ElPagination>
    </div>
    <!-- 弹出层修改 -->
    <el-dialog v-model="alterShow" title="修改" draggable>
      <!-- 修改的部分 -->
      <div class="alter_popup">
        <div>
          <span>角色名称：</span>
          <el-input v-model.trim="roleAlter.name" placeholder="角色名称" clearable />
        </div>
        <div>
          <span>描述信息：</span>
          <el-input v-model.trim="roleAlter.desc" placeholder="描述信息" clearable />
        </div>
        <el-button type="primary" @click="submitAlter" style="align-self: flex-end"
          >修改</el-button
        >
      </div>
    </el-dialog>
    <!--权限弹窗 -->
    <el-dialog v-model="powerShow" title="权限配置" draggable>
      <div>
        <el-tree
          ref="tree"
          :data="dataPermissions"
          show-checkbox
          node-key="id"
          highlight-current
          :props="defaultProps"
        >
          <template #default="{ node, data }">
            <div style="width: 100%; display: flex; justify-content: space-between">
              <span>{{ node.label }}</span>
              <span v-if="data.id != node.label">{{ data.id }}</span>
            </div>
          </template>
        </el-tree>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="powerShow = false">取消</el-button>
          <el-button type="primary" @click="setPermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { post } from "@/request/http";
import { ElMessage, ElMessageBox } from "element-plus";
// 节点
const tree = ref(); //树节点

// 表格数据
let infoList = ref([]);

//弹出的树的数据
let dataPermissions = ref([]);
//设置树形控件的配置
const defaultProps = reactive({
  children: "children",
  label: "label",
});

//传递给分页的信息
let pageInfo = reactive({
  total: 0,
  limit: 20,
});
// 请求列表的数据
let configReq = reactive({
  _gp: "admin.role",
  _mt: "list",
  targetAdminId: "", //管理员id
  page: 1,
  limit: 20,
});

// 添加提交数据
let addData = reactive({
  name: "",
  desc: "",
});

// 是否显示弹出框
let alterShow = ref(false); //修改
let powerShow = ref(false); //授权

// 编辑的角色数据
let roleAlter = reactive({
  name: "",
  desc: "",
  id: 0,
});
// 操作行权限的id
let roleRowId = ref(0);

// 获取表格数据
const getInfo = (): void => {
  post(configReq).then((res) => {
    let { items, total } = res.data;
    if (200 == res.errno) {
      infoList.value = items; //获取表格数据
      pageInfo.total = total; // 获取总页数
    }
  });
};
onMounted(() => {
  getInfo();
});
// 分页切换触发
const changeConfig = (e: { page: number; limit: number }) => {
  Object.assign(configReq, e);
  getInfo();
};

// 添加角色
const addRole = (): void => {
  let { name } = addData;
  if (name ?? name) {
    //??判断左侧是否存在，如果有返回右侧的值
    post({
      _gp: "admin.role",
      _mt: "create",
      role: JSON.stringify(addData),
    })
      .then((res) => {
        if (200 == res.errno) {
          ElMessage.success("添加成功");
          Object.assign(addData, {
            name: "",
            desc: "",
          });
          getInfo();
        }
      })
      .catch((err) => {
        console.log(err);
      });
    return;
  }
  ElMessage.error("角色名称为必填");
};

// 弹出删除确认
const showDele = (id: number) => {
  ElMessageBox.confirm("确认删除该角色", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleRole(id);
    })
    .catch(() => {
      ElMessage.info("已取消");
    });
};
// 删除角色
const deleRole = (id: number): void => {
  post({
    _gp: "admin.role",
    _mt: "delete",
    roleId: id,
  }).then((res) => {
    if (200 == res.errno) {
      ElMessage.success("删除成功");
      getInfo();
    }
  });
};

//弹出修改
const editRole = (data: {}) => {
  Object.assign(roleAlter, { name: "", desc: "", id: 0 });
  Object.assign(roleAlter, data); //修改配置
  alterShow.value = true; //显示修改弹出框
};
// 修改角色
const submitAlter = (): void => {
  let { name } = roleAlter;
  if (name ?? name) {
    post({
      _gp: "admin.role",
      _mt: "update",
      role: JSON.stringify(roleAlter),
    })
      .then((res) => {
        getInfo(); //刷新数据
        alterShow.value = false; //关闭修改弹出框
        ElMessage.success("修改成功");
      })
      .catch((err) => {
        console.log(err);
      });
  } else {
    ElMessage.error("角色名称不能为空");
  }
};

// 角色授权
const getPermission = (id: number) => {
  //获取当前的权限
  //获取对应id的权限列表
  powerShow.value = true;
  roleRowId.value = id;
  post({
    _gp: "admin.role",
    _mt: "permissionList",
    roleId: id,
  }).then((res) => {
    let { systemPermissions, assignedPermissions } = res.data;
    dataPermissions.value = systemPermissions;
    tree.value.setCheckedKeys(assignedPermissions);
  });
};

const setPermission = () => {
  //设置当前权限
  //设置权限，发送请求
  post({
    _gp: "admin.role",
    _mt: "permissionSet",
    roleSetPermissionDTO: JSON.stringify({
      roleId: roleRowId.value,
      permissions: tree.value.getCheckedKeys(),
    }),
  }).then((res) => {
    powerShow.value = false; //关闭权限弹出框
    ElMessage.success("配置成功");
  });
};
</script>

<style scoped lang="less">
.top_box {
  & span {
    font-size: 0.8rem;
  }
}

.el-input {
  width: 200px;
  margin-right: 15px;
}

.alter_popup {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
